package service

import (
	"context"
	"database/sql"
	"time"

	"goserver/internal/model"
)

type StatsService struct {
	db *sql.DB
}

func NewStatsService(db *sql.DB) *StatsService {
	return &StatsService{db: db}
}

// 消息统计数据
type MessageStats struct {
	Date        string `json:"date"`
	TotalCount  int    `json:"total_count"`
	SuccessRate float64 `json:"success_rate"`
	FailCount   int    `json:"fail_count"`
	AvgLatency  float64 `json:"avg_latency"`
}

// 设备统计数据
type DeviceStats struct {
	Date         string `json:"date"`
	ActiveCount  int    `json:"active_count"`
	OnlineRate   float64 `json:"online_rate"`
	MessageCount int    `json:"message_count"`
}

// 获取消息统计
func (s *StatsService) GetMessageStats(ctx context.Context, startDate, endDate time.Time) ([]MessageStats, error) {
	query := `
		SELECT 
			DATE(create_time) as date,
			COUNT(*) as total_count,
			COALESCE(SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) * 100.0 / NULLIF(COUNT(*), 0), 0) as success_rate,
			SUM(CASE WHEN status = 2 THEN 1 ELSE 0 END) as fail_count,
			COALESCE(AVG(TIMESTAMPDIFF(MICROSECOND, create_time, update_time)) / 1000000.0, 0) as avg_latency
		FROM wqyf_messages_1
		WHERE create_time BETWEEN ? AND ?
		GROUP BY DATE(create_time)
		ORDER BY date DESC
	`

	rows, err := s.db.QueryContext(ctx, query, startDate, endDate)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var stats []MessageStats
	for rows.Next() {
		var stat MessageStats
		if err := rows.Scan(&stat.Date, &stat.TotalCount, &stat.SuccessRate, &stat.FailCount, &stat.AvgLatency); err != nil {
			return nil, err
		}
		stats = append(stats, stat)
	}

	return stats, nil
}

// 获取设备统计
func (s *StatsService) GetDeviceStats(ctx context.Context, startDate, endDate time.Time) ([]DeviceStats, error) {
	query := `
		SELECT 
			DATE(create_time) as date,
			COUNT(DISTINCT robot_id) as active_count,
			COALESCE(COUNT(DISTINCT CASE WHEN status = 1 THEN robot_id END) * 100.0 / NULLIF(COUNT(DISTINCT robot_id), 0), 0) as online_rate,
			COUNT(*) as message_count
		FROM wqyf_messages_1
		WHERE create_time BETWEEN ? AND ?
		GROUP BY DATE(create_time)
		ORDER BY date DESC
	`

	rows, err := s.db.QueryContext(ctx, query, startDate, endDate)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var stats []DeviceStats
	for rows.Next() {
		var stat DeviceStats
		if err := rows.Scan(&stat.Date, &stat.ActiveCount, &stat.OnlineRate, &stat.MessageCount); err != nil {
			return nil, err
		}
		stats = append(stats, stat)
	}

	return stats, nil
}

// 获取机器码使用统计
func (s *StatsService) GetRobotCodeStats(ctx context.Context) (map[string]int, error) {
	query := `
		SELECT 
			status,
			COUNT(*) as count
		FROM wqyf_robot_codes
		GROUP BY status
	`

	rows, err := s.db.QueryContext(ctx, query)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	stats := make(map[string]int)
	for rows.Next() {
		var status int
		var count int
		if err := rows.Scan(&status, &count); err != nil {
			return nil, err
		}
		switch status {
		case 0:
			stats["disabled"] = count
		case 1:
			stats["active"] = count
		}
	}

	// 获取过期的机器码数量
	query = `
		SELECT COUNT(*) 
		FROM wqyf_robot_codes 
		WHERE status = 1 AND expire_time < NOW()
	`
	var expiredCount int
	if err := s.db.QueryRowContext(ctx, query).Scan(&expiredCount); err != nil {
		return nil, err
	}
	stats["expired"] = expiredCount

	return stats, nil
} 